﻿using System;
using System.Linq;
using System.Web.Mvc;
using Fuse8.ContentManagementFramework.Administration.Models;
using Fuse8.ContentManagementFramework.BizFacade.Services;
using Fuse8.ContentManagementFramework.Domain;
using Fuse8.ContentManagementFramework.SystemFacade;
using Fuse8.ContentManagementFramework.Web.Etc;
using Fuse8.ContentManagementFramework.Web.MvcPowered;
using Fuse8.DomainFramework.BusinessService;
using Telerik.Web.Mvc;

namespace Fuse8.ContentManagementFramework.Administration.Controllers
{
    public class CmsTemplateController : CmsAdminController<CmsTemplate>
    {
        #region Fields

        private readonly IEntityBusinessService<CmsTemplate, int> _templateService = new BusinessServiceFacade<CmsTemplate, int>();
        private readonly CmsPageService _pageService = new CmsPageService();
        #endregion Fields

        public ActionResult Index(int? pageSize)
        {
            int currentPageSize = pageSize ?? DefaultPageSize;

            var data = _templateService.FindAll();

            ViewBag.PageSize = currentPageSize;
            ViewBag.Total = data.Count();

            return View(data);
        }

        [GridAction]
        public ActionResult _Index(int? pageSize)
        {
            var data = _templateService.FindAll();

            return View(
                   new GridModel<CmsTemplate>
                   {
                       Data = data
                   });
        }

        public ActionResult Add()
        {
            return View(new CmsAdminTemplateModel(new CmsTemplate()));
        }

        [HttpPost]
        public ActionResult Add(CmsAdminTemplateModel model)
        {
            ActionResult result = null;

            if (model != null)
            {
                if (ModelState.IsValid)
                {
                    model.TemplateRegions = CmsTemplateRegionResolver.ResolveRegionsFromTemplate(model.TemplateType, model.TemplateUrl);

                    using (var transaction = new BusinessServiceTransaction<CmsTemplate>().With<CmsTemplateRegion>())
                    {
                        _templateService.Add(model);
                        transaction.Commit();
                    }

                    result = RedirectToAction("Index");
                }
            }

            return result ?? View(model);
        }

        public ActionResult Edit(int id)
        {
            CmsTemplate data = null;

            if (id > 0)
            {
                data = _templateService.FindOne(id);
            }

            return View(
                new CmsAdminTemplateModel(
                    data ?? new CmsTemplate()));
        }

        [HttpPost]
        public ActionResult Edit(CmsAdminTemplateModel model)
        {
            ActionResult result = null;

            if (model != null)
            {
                if (ModelState.IsValid)
                {
                    model.TemplateRegions = CmsTemplateRegionResolver.ResolveRegionsFromTemplate(model.TemplateType, model.TemplateUrl);

                    using (var transaction = new BusinessServiceTransaction<CmsTemplate>().With<CmsTemplateRegion>())
                    {
                        _templateService.Save(model);

                        transaction.Commit();
                    }

                    result = RedirectToAction("Index");
                }
            }

            return result ?? View(model);
        }

        public ActionResult TemplateDetails(int id)
        {
            ActionResult result = null;

            if (id > 0)
            {
                var data = _templateService.FindOne(id);
                if (data != null)
                {
                    result = PartialView(data);
                }
            }

            return result ?? PartialView(new CmsTemplate());
        }

        public ActionResult ShowRegions(int id)
        {
            ActionResult result = null;

            if (id > 0)
            {
                var data = _templateService.FindOne(id);
                if (data != null)
                {
                    var tempTemplateData = new TempDataDictionary();

                    tempTemplateData.Add(CmsConfiguration.ContextTemplateKey, data);

                    result = new CmsViewResult
                    {
                        IsForPreview = true,
                        TemplateType = data.TemplateType,
                        ViewName = string.Format("{0} preview", data.TemplateName),
                        MasterName = data.TemplateUrl,
                        ViewData = ViewData,
                        TempData = tempTemplateData
                    };
                }
            }

            return result ?? new EmptyResult();
        }

        protected override bool _Delete(int id)
        {
            var pages = _pageService.FindAllByTemplateId(id);

            if (pages.Any())
            {
                throw new Exception("This template cannot be deleted because there are pages (or old page revisions) using it");
            }
            _templateService.Remove(id);
            return true;
        }
    }
}